<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2020/6/6  18:07
 */

// 获取当前域名
function getDomain(){
    return $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'];
}

//阿里OSS访问域名
function oss_domain(){
    return $_SERVER['REQUEST_SCHEME'] .'://'.env('ALIYUN_OSS_VISIT','').'/';
}

/**
 *获取唯一订单号
 * @return string
 */
function order_number(){
    return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

//公共方法
function policyMessageFormat($status, $message = '权限不足!',$code=405)
{

    if(!$status) {
        throw new \App\Exceptions\PolicyException('无权限',$code);
    }
    return true;
}

/**
 * 获取上传文件名
 */
function pathName(){
    // 保存路径
    $saveName = 'wxhead/' . date('Ymd') . '/';

    // 全路径
    $path = 'upload/' . $saveName;
    // 验证文件夹是否存在
    if(!is_dir($path)){
        // 不存在则创建
        mkdir($path,0777,true);
    }

    // 获取图片名称
    $imageName = md5(time()) . '.jpg';
    $pathName = 'upload/'.$saveName . $imageName;
    return $pathName;
}

/**
 * 下载微信头像
 */
function getWxHead($imageUrl){
    //dd($imageUrl);die;
    // 保存路径
    $saveName = 'wxhead/' . date('Ymd') . '/';

    // 全路径
    $path = 'upload/' . $saveName;
    // 验证文件夹是否存在
    if(!is_dir($path)){
        // 不存在则创建
        mkdir($path,0777,true);
    }

    // 获取图片名称
    $imageName = md5(time()) . '.jpg';

    downloadImages($imageUrl, $path . $imageName);

    return '/upload/'.$saveName . $imageName;

}

/**
 * 从网上下载图片保存到服务器
 * @param $url 图片网址
 * @param $path 保存到服务器的路径
 */
function downloadImages($url,$path) {
    $img = getcurl($url);
    //保存的文件名称用的是链接里面的名称
    $fp = fopen($path,'w');
    fwrite($fp, $img);
    fclose($fp);
}

/**
 * 获取curl 返回数据
 * @param $url
 * @return bool|string
 */
function getcurl($url){
    $ch = curl_init ($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false); // 绕过ssl
    $curl = curl_exec($ch);
    curl_close($ch);

    return $curl;
}

function replaceHtml($data){
    return preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", " ", strip_tags($data));
}

/**
 * 时间 H:i:s 转 s
 * @User yaokai
 * @param $his
 * @return float|int
 */
function HisToS($his)
{
    $str = explode(':', $his);

    $len = count($str);
    if ($len == 3) {
        $time = $str[0] * 3600 + $str[1] * 60 + $str[2];
    } elseif ($len == 2) {
        $time = ($str[0] * 60 + $str[1]) * 60;
    } elseif ($len == 1) {
        $time = $str[0];
    } else {
        $time = 0;
    }
    return $time;
}

/**
 * 时间 s 转 H:i:s
 * @User yaokai
 * @param $seconds
 * @return string
 */
function SToHis($seconds)
{
    $seconds = (int)$seconds;
    $time = '';
    if ($seconds > 3600) {
        if ($seconds > 86400) {
            $days = (int)($seconds / 86400);
            $seconds = $seconds % 86400;//取余
            $time .= $days . " 天 ";
        }
        $hours = intval($seconds / 3600);
        $minutes = $seconds % 3600;//取余下秒数
        $time .= $hours . " 小时 " . gmstrftime('%M 分钟 %S 秒', $minutes);
    } elseif ($seconds > 60) {
        $time = gmstrftime('%M 分钟 %S 秒', $seconds);
    } else {
        $time = gmstrftime('%S 秒', $seconds);
    }
    return $time;
}

/**
 * @param $data json
 * @return string
 */
function liantu_qr_src($data){
    return "https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=".json_encode($data);
}

/**
 * 獲取隨機數
 * @return string0
 */
function getRandCode($len = 16){
    $arr = [
        'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'
    ];
    $tmpstr = '';

    for($i = 0;$i < $len;$i++){
        $tmpstr .= $arr[rand(0,count($arr) - 1)];
    }

    return $tmpstr;
}

/**
 * 获取订单号
 */
function getOrder()
{
    return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}

/**
 * 兑换码
 */
function redemption_code()
{
    return time().mt_rand(10000,99999);
}

/**
 * 获取控制器与方法
 * @return array
 */
function myGetRouteName(){
    $action = \Route::current()->getActionName();
    list($class, $method) = explode('@', $action);

    $rearr = [
        'model' => str_replace(
            '\\',
            '.',
            str_replace(
                'App\\Http\\Controllers\\',
                '',
                trim(
                    implode('\\', array_slice(explode('\\', $class), 0, -1)),
                    '\\'
                )
            )
        ),
        'controller' => str_replace(
            'Controller',
            '',
            substr(strrchr($class, '\\'), 1)
        ),
        'method' => $method
    ];

    return $rearr;
}

/**
 * 用于权限管理判断路由是否有权限实现
 * @param $url                    路由名称
 * @param array $right_list       该账号有那些权限
 * @param array $get_routes       根据url获取控制器路由
 */
function permission($url = '', $right_list = [], $get_routes = [])
{
    if($url == '')return false;

    $get_routes_bool = $get_routes[url_param($url)]??'';

    if(in_array('all', $right_list))return true;

    if(in_array($get_routes_bool, $right_list)){
        return true;
    }else{
        return false;
    }
}

/**
 * 將路由路徑的參數清除掉  比如  /admin/{id}  清掉id
 * @param string $url
 * @return string
 */
function url_param($url = '')
{
    $uri_array = explode('/',$url);
    $uri_string = '';

    for($i=0;$i<count($uri_array);$i++){
        if(strpos($uri_array[$i],'{') !== false)continue;

        if (is_numeric($uri_array[$i]))continue;

        if($uri_array[$i] == '')continue;

        $uri_string .= '/'.$uri_array[$i];
    }

    return $uri_string;
}
